package com.hll.spring_book.controller;

import com.google.zxing.WriterException;
import com.hll.spring_book.util.QRCodeGenerator;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: Mr.Hu
 * @create: 2021-04-05 11:43
 */
@RequestMapping("/qr")
@Controller
public class QrCodeController {
  @GetMapping("qrCode")
  public void getQRImageByOutputStream(
      @RequestParam("message") String message, HttpServletResponse response) throws IOException {
    byte[] qrCode = null;
    try {
      qrCode = QRCodeGenerator.getQRCodeImage(message, 360, 360);
    } catch (WriterException e) {
      e.printStackTrace();
    }
    // Header设置文件类型（ContentType不设置也没事）
    response.setContentType(MediaType.IMAGE_PNG_VALUE);
    assert qrCode != null;
    response.getOutputStream().write(qrCode);
  }
}
